package com.example.ranl_offershow.Controller;

import com.example.ranl_offershow.Utils.EventDispatcher;
import com.example.ranl_offershow.Utils.MessageDispatcher;
import com.example.ranl_offershow.Utils.MessageUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.PrintWriter;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class MsgController {
    /**
     * 接收微信服务器发送来的消息
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/wxRequest")
    public void doPost(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, String> messageMap = MessageUtil.parseXml(request);
            System.out.println("消息："+messageMap.get("Content"));
            String type = messageMap.get("MsgType");
            if(MessageUtil.REQ_MESSAGE_TYPE_EVENT.equals(type)){
                //事件处理
                EventDispatcher.processEvent(messageMap);
            }else {
                request.setCharacterEncoding("UTF-8");
                response.setCharacterEncoding("UTF-8");
                //消息处理
                String data = MessageDispatcher.processMessage(messageMap);
                PrintWriter out = response.getWriter();
                out.print(data);
                out.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
